package net.kts.attraction.subway;

import java.util.List;

import net.kts.attraction.subway.positon.SubwayPositionDaoSQLite;
import net.kts.attraction.subway.positon.SubwayTransferStationDaoSQLite;
import net.kts.attraction.subway.positon.model.SubwayPosition;
import net.kts.attraction.subway.positon.overlay.MyItemizedOverlay;
import net.kts.attraction.subway.smallpass.model.StationName;
import net.kts.attraction.subway.smallpass.sqlite.SubwayNameDaoSQLite;
import net.kts.define.SQLiteDatabaseStr;
import net.kts.location.MyLocationManager;
import net.kts.main.R;
import net.kts.setting.language.LanguageUtil;
import net.kts.util.url.mylocation.MyLocationDrawable;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class SubwaySearchMap extends MapActivity {
	
	
	private MapView mapView = null;
//	private LocationManager locationManager = null;
	private LocationListener locationListener = null;
	private SubwayPositionDaoSQLite positionDaoSQLite = null;
//	private MyLocationOverlay myLocationOverlay = null;
	private SubwayNameDaoSQLite subwayNameDaoSQLite = null;
	private SubwayTransferStationDaoSQLite subwayTransferStationDaoSQLite = null;
	
	private Handler uiCallbackHandler = null;
	private ProgressDialog progressDialog = null;
	
	private MyLocationDrawable myLocationDrawable = null;
	

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.attraction_subway_search_map);
		
		this.progressDialog = new ProgressDialog(this);//ProgressDialog.show(this, "Search Subway Position", "Searching...");
		this.progressDialog.setMessage("Subway Searching....");
		this.progressDialog.show();
		
		
//		this.locationListenerInit();
		handlerInit();
		
//		SQLiteDatabaseStr.pakageName, SQLiteDatabaseStr.dbFileName, SQLiteDatabaseStr.assertPath);
		
		
		
		this.mapView = (MapView)findViewById(R.id.subwaySearchMap);
		
		this.mapView.setBuiltInZoomControls(true);
		this.mapView.getController().setZoom(15);
		
//		this.locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		
		
//		this.locationManager.requestLocationUpdates(provider, 0, 0, this.locationListener);
		//this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this.locationListener);
//		this.myLocationOverlay = new MyLocationOverlay(this, this.mapView);
//		
//		
//		this.mapView.getOverlays().add(this.myLocationOverlay);
//        
//        this.myLocationOverlay.enableCompass();
//        this.myLocationOverlay.enableMyLocation();
		
	}
	
	
	
	
	private void handlerInit() {
		// TODO Auto-generated method stub
		
		Drawable drawable = getResources().getDrawable(R.drawable.story_flag_my);
		this.myLocationDrawable = new MyLocationDrawable(drawable);
		
		this.uiCallbackHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
//				super.handleMessage(msg);
				Bundle bundle = msg.getData();
				
				Double lat  = (Double)bundle.get("lat");
				Double lng  = (Double)bundle.get("lng");
				
				Location location = new Location("current");
				location.setLatitude(lat);
				location.setLongitude(lng);
				
				changeLocation(location);
			}
			
		};
	}




	@Override
	protected void onResume() {
		
		
		// TODO Auto-generated method stub
		super.onResume();
		
		if(this.locationListener == null) {
			this.locationListenerInit();
			MyLocationManager.addLocationListener(this.locationListener);
		}
		
//		changeLocation(MyLocationManager.giveMeMyCurrentLocation());
		
		Bundle bundle = new Bundle();
		
		
		Location location = MyLocationManager.giveMeMyCurrentLocation();
		
		bundle.putDouble("lat", location.getLatitude());
		bundle.putDouble("lng", location.getLongitude());
		
		Message msg = new Message();
		msg.setData(bundle);
		
		this.uiCallbackHandler.sendMessage(msg);
		
		GeoPoint point = new GeoPoint((int)(location.getLatitude() * 1000000), (int)(location.getLongitude()* 1000000 ));
		
		this.myLocationDrawable.updateOverlay(new OverlayItem(point, "", ""));
		this.mapView.getOverlays().add(myLocationDrawable);
		
		this.mapView.getController().animateTo(point); 
		
		
		this.subwayTransferStationDaoSQLite = new SubwayTransferStationDaoSQLite(this, SQLiteDatabaseStr.dbFileName, null, 1);
		this.positionDaoSQLite = new SubwayPositionDaoSQLite(this,SQLiteDatabaseStr.dbFileName, null, 1);
		this.subwayNameDaoSQLite = new SubwayNameDaoSQLite(this, SQLiteDatabaseStr.dbFileName, null, 1);
		
		
//		String provider = locationManager.getBestProvider(BestProvider.getBestProviderCriteria(), true);
//		this.locationManager.requestLocationUpdates(provider, 0, 0, this.locationListener);
		
//		this.myLocationOverlay.enableMyLocation();
//		
//		this.myLocationOverlay.runOnFirstFix(new Runnable() {
//			
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				mapView.getController().setCenter(myLocationOverlay.getMyLocation());
//				
////				Location location = new Location("current");
//				GeoPoint geoPoint = myLocationOverlay.getMyLocation();
//								
//				Bundle bundle = new Bundle();
//				bundle.putDouble("lat", geoPoint.getLatitudeE6() * 0.000001);
//				bundle.putDouble("lng", geoPoint.getLongitudeE6() * 0.000001);
//				
//				Message msg = new Message();
//				msg.setData(bundle);
//				
//				uiCallbackHandler.sendMessage(msg);
//				
////				changeLocation(location);
//			}
//		});
		
	}




	private void locationListenerInit() {
		
		this.locationListener = new LocationListener() {
			
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				// ���⼭ ������!~
//				Toast.makeText(getBaseContext(), "New location latitude ["  +
//			    		lat + "] longitude [" + lng + "]", Toast.LENGTH_SHORT).show();
				changeLocation(location);
			}
		};
		
	}
	
	public void changeLocation(Location location) {
		//this.locationFlag = true;
		
		
//		SubwayPositionItemizedOverlay itemizedOverlay = null;
		MyItemizedOverlay itemizedOverlay = null;
		List<SubwayPosition> positionList = this.positionDaoSQLite.getlocationList(location, -1);
		StationName stationName = null;
		
			
		String line = null;
		String walkTime = null;
		double distance = 0;
		
//		SubwayPosition position = this.getNearPosition(location, positionList);
		
		if(positionList != null) {
			itemizedOverlay = new MyItemizedOverlay(getResources().getDrawable(R.drawable.marker_subway), this.mapView);
			for(SubwayPosition position : positionList) {
				
				distance = location.distanceTo(position);
				position.setDistance(distance);
				
				stationName = this.subwayNameDaoSQLite.selectStationName(position.getStationCode(), LanguageUtil.getCurrentLanguage());
				
				line = this.getLine(stationName);
				walkTime = this.getWalkTime(position.getDistance());
				
				OverlayItem item = new OverlayItem(new GeoPoint((int)(position.getLatitude() * 1000000), (int)(position.getLongitude() * 1000000)), stationName.getStationName(), line + "||" + (int)position.getDistance() + "||" + walkTime);
				
				itemizedOverlay.addOverlay(item);

			}			
			this.mapView.getOverlays().add(itemizedOverlay);
		}
		else {
//			Toast.makeText(getBaseContext(), "Not Found Subway", Toast.LENGTH_SHORT).show();
		}
		
		
		this.progressDialog.dismiss();
		
//		if(position != null) {
//			itemizedOverlay = new MyItemizedOverlay(getResources().getDrawable(R.drawable.marker), this.mapView);
//			OverlayItem item = new OverlayItem(new GeoPoint((int)(position.getLatitude() * 1000000), (int)(position.getLongitude() * 1000000)), "�ų�����", "Line : 9");
//			
//			itemizedOverlay.addOverlay(item);
//			
//			this.mapView.getOverlays().add(itemizedOverlay);
//		}
//		else {
//			Toast.makeText(getBaseContext(), "Not Found Subway", Toast.LENGTH_SHORT).show();
//		}
		
//		String temp = "";
//		temp += "location lat : " + location.getLatitude();
//		temp += "location lng : " + location.getLongitude();
//		if(position != null) {
//			temp += "subway lat : " + position.getLatitude();
//			temp += "subway lng : " + position.getLongitude();
//			temp += " distance : " + position.getDistance();
//		}
//		else {
//			temp += " Subway NotFound!!";
//		}
//		
//		Toast.makeText(getBaseContext(), temp, Toast.LENGTH_SHORT).show();
	}
	
	// �˻���� 100���� �ȴµ� 100������ �Ǹ��ٰ� �Ѵ� ;; ���� �ȴ� ����� �ü� 4km�̶�.. �ʼ� 1.11m ;;
		private String getWalkTime(double distance) {
			// TODO Auto-generated method stub
			
			int dis = (int)distance;
			
			int minute = dis/ 60;
			
			return String.valueOf(minute + 1);
		}




		private String getLine(StationName stationName) {
			
			String line = null;
			
			if(stationName.getStationCodeList() == null) {
				return getLineName(stationName.getLineNum());
			}
			
			line = "";
			
			List<Integer> lineList = this.subwayTransferStationDaoSQLite.selectTransferStation(stationName.getStationCodeList().get(0));
			
			for(int indexI = 0 ; indexI < lineList.size(); ++ indexI) {
				if(indexI != 0) {
					line += ", ";
				}
				
				line += getLineName(lineList.get(indexI));
				
			}
			
			return line;
		}
		
		
		private String getLineName(int lineNum) {
			
			String returnStr = null;
			
			switch (lineNum) {
			case 10:
				returnStr = "Bundang";
				break;
			case 11:
				returnStr = "Gyeongui";
				break;
			case 12:
				returnStr = "Incheon1";
				break;
			case 13:
				returnStr = "Airport_railroad";
				break;
			case 14:
				returnStr = "Jungang";
				break;
			case 15 :
				returnStr = "Gyongchun";
				break;
			case 16 :
				returnStr = "Sinbundang";
				break;
			default :
				returnStr = String.valueOf(lineNum);
				break;
			}
			
			
			
			return returnStr;
		}
	
	private SubwayPosition getNearPosition(Location location, List<SubwayPosition> positionList) {
		
		SubwayPosition position = null;
		SubwayPosition temp = null;
		double distance = 0;
		
		if(positionList == null) {
			return position;
		}
		
		if(positionList.size() == 1) {
			return positionList.get(0);
		}
		
		for(int indexI = 0 ; indexI < positionList.size() ; ++indexI) {
			temp = positionList.get(indexI);
			distance = location.distanceTo(temp);
			temp.setDistance(distance);
			
			
			if(position == null) {
				position = temp;
			}
			else {
				if(position.getDistance() > temp.getDistance()) {
					position = temp;
				}
			}
			
		}
		
 		
		return position;
		
	}
	

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}




	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
//		this.locationManager.removeUpdates(this.locationListener);
//		this.myLocationOverlay.disableMyLocation();
		
		this.subwayTransferStationDaoSQLite.close();
		this.subwayNameDaoSQLite.close();
		this.positionDaoSQLite.close();
	}

	
	
	
}
